const query = require('../../db/index');

// 获取所有文章
exports.getAllArticles = async (req, res) => {
    try {
        // 分页参数
        console.log(req.query);
        const { page, pageSize } = req.query;
        console.log(page, pageSize);
        const offset = (page - 1) * pageSize;

        // 查询文章数量
        const countSQL = `
            SELECT COUNT(*) AS total FROM article;
        `;
        const countResult = await query(countSQL);
        const total = countResult[0].total;
        const totalPages = Math.ceil(total / pageSize);

        // 查询文章及其关联的标签
        const getArticlesSQL = `
            SELECT a.*, IFNULL(GROUP_CONCAT(t.name), '') AS tagNames
            FROM article a
            LEFT JOIN settags st ON a.articleId = st.articleId
            LEFT JOIN tags t ON st.tagsId = t.tagsId
            GROUP BY a.articleId
            ORDER BY a.time DESC
            LIMIT ?, ?;
        `;
        const articles = await query(getArticlesSQL, [offset, parseInt(pageSize)]);

        // 将tagNames字段处理为数组
        articles.forEach(article => {
            article.tagNames = article.tagNames ? article.tagNames.split(',') : [];
        });

        // 返回结果
        return res.dispatch(200, "Success", { articles, totalPages });
    } catch (error) {
        // 如果出现错误，返回 500 错误
        return res.dispatch(500, "Internal Server Error");
    }
};

// 添加文章
exports.addArticle = async (req, res) => {
    try {
        let { time, title, content, categoriesId, tagsId } = req.body;
        let likeCount = 0
        let browse = 0
        console.log(likeCount, browse);
        // 开始事务
        await query("START TRANSACTION");

        try {
            // 插入文章数据
            const insertArticleSQL = "INSERT INTO article (time, title, content, likeCount, browse, categoriesId) VALUES (?, ?, ?, ?, ?, ?)";
            const articleValues = [time, title, content, likeCount, browse, categoriesId];
            const articleResult = await query(insertArticleSQL, articleValues);
            const articleId = articleResult.insertId;
            console.log('articleId', articleId);

            // 将标签与文章关联存储到 settags 表中
            if (tagsId) {
                // 如果 tagsId 存在
                const tagsArray = tagsId.split(','); // 将逗号隔开的字符串分割成数组
                if (tagsArray.length > 0) {
                    const insertSetTagsSQL = "INSERT INTO settags (articleId, tagsId) VALUES ?";
                    // 构建插入数据的数组
                    const setTagsValues = tagsArray.map(tagId => [articleId, tagId]);
                    await query(insertSetTagsSQL, [setTagsValues]);
                }
            }

            // 提交事务
            await query("COMMIT");
            // 返回成功的响应
            return res.dispatch(201, "Article added successfully");
        } catch (error) {
            // 发生错误时回滚事务
            await query("ROLLBACK");
            console.error("Error in adding article:", error);
            return res.dispatch(500, "Internal Server Error: Failed to save article");
        }
    } catch (error) {
        // 如果出现其他错误，返回 500 错误
        console.error("Error in addArticle controller:", error);
        return res.dispatch(500, "Internal Server Error");
    }
}
// 删除文章
exports.deleteArticle = async (req, res) => {
    try {
        // 从请求参数中获取文章ID
        const articleId = req.query.articleId;
        console.log('articleId', articleId);
        // 如果文章ID不存在，返回 400 错误
        if (!articleId) {
            return res.dispatch(400, "Bad Request: Article ID is required");
        }

        // 使用文章ID执行数据库删除操作
        const sql = "DELETE FROM article WHERE articleId = ?";
        const values = [articleId];

        await query(sql, values);

        // 返回成功的响应
        return res.dispatch(200, "Article deleted successfully");
    } catch (error) {
        // 如果删除文章出错，返回 500 错误
        return res.dispatch(500, "Internal Server Error: Failed to delete article");
    }
};

// 编辑文章
exports.updateArticle = async (req, res) => {
    try {
        // 从请求体中获取新的文章内容
        const { articleId, title, content } = req.body;

        // 检查是否提供了新的文章内容
        if (!title || !content) {
            return res.dispatch(400, "Bad Request: Title and content are required");
        }

        // 更新数据库中指定ID的文章内容
        const sql = "UPDATE article SET title = ?, content = ? WHERE articleId = ?";
        const values = [title, content, articleId];

        await query(sql, values);

        // 返回成功的响应
        return res.dispatch(200, "Article updated successfully");
    } catch (error) {
        // 如果更新文章出错，返回 500 错误
        console.error(error);
        return res.dispatch(500, "Internal Server Error: Failed to update article");
    }
};
